package cn.com.server.export;

import cn.com.common.Constant;
import cn.com.common.RegistryInfo;
import cn.com.common.URI;
import cn.com.common.utils.IPHelper;
import cn.com.registry.EtcdRegistryServiceFactory;
import cn.com.registry.RegistryConfig;
import cn.com.registry.RegistryFactory;
import cn.com.registry.RegistryService;
import cn.com.rpc.NettyServer;
import cn.com.server.dict.AppDictionary;
import cn.com.server.handler.ZhuRongHandler;
import cn.com.server.push.AppPushService;
import cn.com.server.push.Push;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jiaming
 */
public class ZhurongExport implements Export {

    private static final Map<String, NettyServer> serverMap = new ConcurrentHashMap<>();

    private RegistryFactory registryFactory = new EtcdRegistryServiceFactory();

    @Override
    public void export(RegistryConfig registryConfig, URI uri) {
        //服务发布步骤：
        //1.启动本地服务
        startServer(uri);
        //2.注册服务到注册中心
        int port = registryConfig.getPort();
        String host = registryConfig.getHost();
        String address = host + ":" + port;
        RegistryService registry = registryFactory.getRegistry(address);
        RegistryInfo registryInfo = new RegistryInfo();
        registryInfo.setAppName(uri.getServiceName());
        registryInfo.setHost(uri.getHost());
        registryInfo.setPort(uri.getPort());
        registryInfo.setRoot(registryConfig.getRoot());
        registry.register(registryInfo);
        //3.拉取客户端注册列表
        RegistryInfo onListenerInfo = new RegistryInfo();
        onListenerInfo.setListener(true);
        AppDictionary appListener = new AppDictionary();
        registry.onListener(appListener);
        registry.subscribe(onListenerInfo, Constant.APPLICATION_PATH);
    }

    /**
     * 启动本地netty server端
     *
     * @param uri
     */
    private void startServer(URI uri) {
        Push push = new AppPushService();
        ZhuRongHandler handler = new ZhuRongHandler(push);
        NettyServer nettyServer = new NettyServer(uri, handler);
        nettyServer.start();
    }

}
